package org.mysterylab.utopiaframework.util.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 以静态变量的形式来保存 Spring 的 Application Context. 这样可以很方便地在在代码中取出 Application Context.
 * 
 * @author zhouych
 */
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
	
	private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);
	
	/**
	 * Spring 的 Application Context
	 */
	private static ApplicationContext applicationContext;

	/**
	 * 实现 {@link ApplicationContextAware} 接口, 注入 context 到静态变量中.
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		logger.debug("注入 ApplicationContext 到 SpringContextHolder: "
				+ applicationContext);
		
		if (SpringContextHolder.applicationContext != null) {
			logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为: "
					+ SpringContextHolder.applicationContext);
		}
		SpringContextHolder.applicationContext = applicationContext;
	}

	@Override
	public void destroy() throws Exception {
		SpringContextHolder.clear();
	}

	public static ApplicationContext getApplicationContext() {
		assertContextInjected();
		return applicationContext;
	}

	/**
	 * 检查 ApplicationContext 不为空.
	 */
	private static void assertContextInjected() {
		if (applicationContext == null) {
			throw new IllegalStateException("applicaitonContext未注入, 请在 applicationContext.xml 中定义 SpringContextHolder");
		}
	}
	
	/**
	 * 清除 SpringContextHolder 中的 ApplicationContext 为 null.
	 */
	public static void clear() {
		logger.debug("清除 SpringContextHolder 中的 ApplicationContext: "
				+ applicationContext);
		applicationContext = null;
	}
	
	/**
	 * 从静态变量 applicationContext 中取得 bean, 自动转型为所赋值对象的类型.
	 * 
	 * @param <T>
	 * @param name
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		assertContextInjected();
		return (T) applicationContext.getBean(name);
	}
	
	/**
	 * 从静态变量 applicationContext 中取得 bean, 自动转型为所赋值对象的类型.
	 * 
	 * @param <T>
	 * @param requiredType
	 * @return
	 */
	public static <T> T getBean(Class<T> requiredType) {
		assertContextInjected();
		return applicationContext.getBean(requiredType);
	}
}
